import { createRouter, createWebHistory, RouteLocationNormalized, RouteRecordRaw, useRoute } from 'vue-router';
import { onUnmounted } from 'vue/dist/vue';
import defaultRoutes from './defaultRoutes';
import { basePATH } from '@/config/global';
import { deepCopy, filter, forEach, nextId } from '@/soar';

const regExp = /^(http:\/\/|https:\/\/|ws:\/\/|ftp:\/\/|\/).*/;

// 关于单层路由，meta 中设置 { single: true } 即可为单层路由，{ hidden: true } 即可在侧边栏隐藏该路由

// 处理路由路径和名称
export function pretreatment(routes) {
  forEach(routes, (x, p) => {
    if (!regExp.test(x.path)) {
      x.path = `${p.path ?? ''}/${x.path}`;
    }
    x.name ??= `s${nextId()}`;
  });
}
pretreatment(defaultRoutes);

function getDefaultRoutes(): RouteRecordRaw[] {
  return deepCopy(defaultRoutes, true);
}

export function getCurrentRoute() {
  return router.currentRoute.value;
}

/**
 * 获取当前活动路由
 * @param maxLevel
 */
export function getActive(): string {
  const route = router.currentRoute.value;
  if (!route?.path) {
    return '';
  }
  return `/${route.path
    .split('/')
    .filter((item: string) => item)
    .join('/')}`;
}

/**
 * 获取本地路由(权限处理)
 */
export function getLocalRoutes() {
  // 自动导入modules文件夹下所有ts文件
  const modules = import.meta.globEager('./modules/**/*.ts');
  // 路由暂存
  const routeModuleList: Array<RouteRecordRaw> = [];
  // 读取所有模块路由数据
  Object.keys(modules).forEach((key) => {
    // @ts-ignore
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routeModuleList.push(...modList);
  });
  // 权限过滤
  return filter(routeModuleList, (route) => {
    const { meta } = route;
    return !(meta && meta.auth && !meta.auth());
  });
}

/**
 * 移除路由
 * @param routes
 */
export function removeRoute(routes) {
  // 移除本地路由
  for (const route of routes) {
    if (router.hasRoute(route.name)) {
      router.removeRoute(route.name);
    }
  }
}

/**
 * 添加路由
 * @param routes
 */
export function addRoute(routes) {
  pretreatment(routes);
  // 添加路由
  for (const route of routes) {
    if (!router.hasRoute(route.name)) {
      router.addRoute(route);
    }
  }
}

/**
 * 刷新路由
 */
export function refreshRoute(routes?) {
  removeRoute(router.getRoutes());
  addRoute(getDefaultRoutes());
  if (routes) {
    addRoute(routes);
  }
}

const router = createRouter({
  history: createWebHistory(basePATH),
  routes: getDefaultRoutes(),
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      behavior: 'smooth',
    };
  },
});

export default router;
